from django.shortcuts import render
from rest_framework.response import Response
from django_redis import get_redis_connection
from decimal import Decimal
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import IsAuthenticated

from goods.models import SKU
from . import serializers
# Create your views here.


class OrderView(APIView):
    """订单确认页面"""
    # 进入视图前进行权限校验
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取购物车勾选的商品数据"""
        # 获取当前用户
        user = request.user

        # 获取redis购物车中被勾选的商品
        redis_conn = get_redis_connection('cart')
        cart_redis = redis_conn.hgetall('cart_%s' % user.id)
        selected_redis = redis_conn.smembers('selected_%s' % user.id)

        # 定义容器存储被勾选的商品信息
        cart = {}
        for sku_id in selected_redis:
            cart[int(sku_id)] = int(cart_redis[sku_id])
        # 查询商品信息
        skus = SKU.objects.filter(id__in=cart.keys())
        # 遍历商品sku对象列表并对其动态添加购物车商品数量信息
        for sku in skus:
            sku.count = cart[sku.id]

        # 定义运费
        freight = Decimal('10.00')

        # 序列化要进行输出的数据
        serializer = serializers.OrderSerializer({'freight': freight, 'skus': skus})

        # 将序列化后的数据响应给前端,状态码默认200
        return Response(serializer.data)


class CommitOrderView(CreateAPIView):
    """订单提交"""
    # 校验用户权限
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = serializers.CommitOrderSerializer
